import React from 'react';

class FormDemo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '双越',
      info: '个人信息',
      city: 'beijing',
      flag: true,
      gender: 'male'
    }
  }
  render() {

    // 受控组件 v-model
    // 非受控组件 - 后面再讲 - 表单里的值没法受state控制
    const inputDemo = <div>
      <p>{this.state.name}</p>
      <label htmlFor="inputName">姓名：</label>{/* 用 htmlFor 代替 for */}
      <input id="inputName" value={this.state.name} onChange={this.onInputChange} />
    </div>

    // textarea - 使用 value
    const textareaDemo = <div>
      <textarea value={this.state.info} onChange={this.onTextareaChange}></textarea>
      <p>{this.state.info}</p>
    </div>

    // select - 使用 value
    const selectDemo = <div>
      <select value={this.state.city} onChange={this.onSelectChange}>
        <option value="beijing">北京</option>
        <option value="shanghai">上海</option>
        <option value="shenzhen">深圳</option>
      </select>
      <p>{this.state.city}</p>
    </div>

    // checkbox - 使用 checked
    const checkboxDemo = <div>
      <input type="checkbox" checked={this.state.flag} onChange={this.onCheckboxChange} />
      <p>{this.state.flag.toString()}</p>
    </div>

    // radio - 使用 checked
    const radioDemo = <div>
      male <input type="radio" name="gender" value="male" checked={this.state.gender === 'male'} onChange={this.onRadioChange} />
            female <input type="radio" name="gender" value="female" checked={this.state.gender === 'female'} onChange={this.onRadioChange} />
      <p>{this.state.gender}</p>
    </div>

    return (
      <div>
        <h4>受控组件 - 表单</h4>
        <h4>1. input</h4>
        {inputDemo}
        <h4>2. textarea</h4>
        {textareaDemo}
        <h4>3. select</h4>
        {selectDemo}
        <h4>4. checkbox</h4>
        {checkboxDemo}
        <h4>5. radio</h4>
        {radioDemo}
      </div>
    )
  }

  // 类似v-model
  onInputChange = (e) => {
    this.setState({
      name: e.target.value
    })
  }

  // 类似v-model
  onTextareaChange = (e) => {
    this.setState({
      info: e.target.value
    })
  }

  onSelectChange = (e) => {
    this.setState({
      city: e.target.value
    })
  }

  onCheckboxChange = () => {
    this.setState({
      flag: !this.state.flag
    })
  }

  onRadioChange = (e) => {
    this.setState({
      gender: e.target.value
    })
  }
}

export default FormDemo;
